package mq

import (
	"fmt"
	"gitee.com/DonHz/cloud-file-storage/config"
	"github.com/streadway/amqp"
	"log"
)

var (
	conn    *amqp.Connection
	channel *amqp.Channel
)

func initChannel() bool {
	if channel != nil {
		return true
	}
	// 获得rabbitmq的一个连接
	var err error
	conn, err = amqp.Dial(config.RabbitURL)
	fmt.Println("尝试建立amqp连接: ", conn)
	if err != nil {
		log.Printf("Failed to connect to RabbitMQ: %v", err)
		return false
	}
	// 打开一个channel
	channel, err = conn.Channel()
	fmt.Println("尝试打开channel: ", channel)
	if err != nil {
		log.Println(err)
		return false
	}
	return true
}

// 发布消息
func Publish(exchange string, routingKey string, msg []byte) bool {
	// 判断channel是否正常
	if !initChannel() {
		return false
	}
	fmt.Println("channel: ", channel)
	// 执行消息发布动作
	err := channel.Publish(
		exchange,
		routingKey,
		false,
		false,
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        msg,
		},
	)
	if err != nil {
		log.Println(err)
		return false
	}
	return true
}
